<template>
  <view class="profile-container">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-blue" :isBack="false">
      <block slot="content">个人信息 </block>
    </cu-custom>

    <!-- 用户信息卡片 -->
    <view class="user-info-card margin-top bg-white">
      <view class="user-header padding">
        <view class="flex align-center">
          <view class="avatar-wrapper" @click="changeAvatar">
            <image
              :src="userInfo.avatar || '/static/images/default-avatar.png'"
              class="cu-avatar xl round"
            ></image>
            <view class="avatar-edit">
              <text class="cuIcon-camera text-white"></text>
            </view>
          </view>
          <view class="flex-sub margin-left">
            <view class="text-xl text-bold">{{
              userInfo.empName || "未知用户"
            }}</view>
            <view class="text-sm text-gray margin-top-xs">
              工号：{{ userInfo.empNo || "暂无" }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 基本信息 -->
    <view class="info-section margin-top bg-white">
      <view class="section-title padding">
        <text class="text-lg text-bold">基本信息</text>
      </view>
      <view class="info-list">
        <view class="info-item flex align-center justify-between padding">
          <view class="flex align-center">
            <text class="cuIcon-people info-icon"></text>
            <text class="margin-left">姓名</text>
          </view>
          <text class="text-gray">{{ userInfo.empName || "暂无" }}</text>
        </view>
        <view class="info-item flex align-center justify-between padding">
          <view class="flex align-center">
            <text
              class="cuIcon-male info-icon"
              v-if="userInfo.sex === 1"
            ></text>
            <text
              class="cuIcon-female info-icon"
              v-else-if="userInfo.sex === 2"
            ></text>
            <text class="cuIcon-people info-icon" v-else></text>
            <text class="margin-left">性别</text>
          </view>
          <text class="text-gray">{{ getSexText(userInfo.sex) }}</text>
        </view>
        <view class="info-item flex align-center justify-between padding">
          <view class="flex align-center">
            <text class="cuIcon-phone info-icon"></text>
            <text class="margin-left">手机号</text>
          </view>
          <text class="text-gray">{{ userInfo.phone || "暂无" }}</text>
        </view>
      </view>
    </view>

    <!-- 工作信息 -->
    <view class="work-section margin-top bg-white">
      <view class="section-title padding">
        <text class="text-lg text-bold">工作信息</text>
      </view>
      <view class="info-list">
        <view class="info-item flex align-center justify-between padding">
          <view class="flex align-center">
            <text class="cuIcon-group info-icon"></text>
            <text class="margin-left">所属部门</text>
          </view>
          <text class="text-gray">{{ userInfo.departName || "暂无" }}</text>
        </view>
        <view class="info-item flex align-center justify-between padding">
          <view class="flex align-center">
            <text class="cuIcon-rank info-icon"></text>
            <text class="margin-left">职位</text>
          </view>
          <text class="text-gray">{{ isAdminLogin ? "管理" : "员工" }}</text>
        </view>
        <!-- 生产员工工种信息 -->
        <view
          v-if="isProductionEmployee"
          class="info-item flex align-center justify-between padding"
        >
          <view class="flex align-center">
            <text class="cuIcon-settings info-icon"></text>
            <text class="margin-left">掌握工种</text>
          </view>
          <view class="work-types">
            <text
              v-for="(workType, index) in userWorkTypes"
              :key="index"
              class="work-type-tag"
              :class="workType.levelClass"
            >
              {{ workType.name }}
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="function-menu margin-top bg-white">
      <view
        class="menu-item flex align-center justify-between padding"
        @click="editProfile"
      >
        <view class="flex align-center">
          <text class="cuIcon-edit menu-icon text-blue"></text>
          <text class="margin-left">编辑资料</text>
        </view>
        <text class="cuIcon-right text-gray"></text>
      </view>
      <view
        class="menu-item flex align-center justify-between padding"
        @click="changePassword"
      >
        <view class="flex align-center">
          <text class="cuIcon-lock menu-icon text-orange"></text>
          <text class="margin-left">修改密码</text>
        </view>
        <text class="cuIcon-right text-gray"></text>
      </view>
      <view
        class="menu-item flex align-center justify-between padding"
        @click="aboutApp"
      >
        <view class="flex align-center">
          <text class="cuIcon-info menu-icon text-purple"></text>
          <text class="margin-left">关于应用</text>
        </view>
        <text class="cuIcon-right text-gray"></text>
      </view>
    </view>

    <!-- 退出登录 -->
    <view class="logout-section margin-top">
      <button class="cu-btn bg-red lg block margin" @click="logout">
        退出登录
      </button>
    </view>
  </view>
</template>

<script>
import authService from "../../src/services/auth.js";
import employeeWorkTypeApi from "../../api/mes/employeeWorkType.js";
import { USER_INFO } from "@/common/util/constants.js";

export default {
  data() {
    return {
      userInfo: {},
      currentRole: null,
      userWorkTypes: [], // 用户掌握的工种
      loginType: "", // 登录类型：employee 或 admin
      settings: {
        pushNotification: true,
        soundAlert: true,
        vibration: false,
        taskReminder: true,
        qualityReminder: true,
      },
    };
  },

  computed: {
    // 判断是否为员工登录
    isEmployeeLogin() {
      return this.loginType == "employee";
    },

    // 判断是否为管理员登录
    isAdminLogin() {
      return this.loginType == "admin";
    },

    // 判断是否为生产员工
    isProductionEmployee() {
      return (
        this.isEmployeeLogin &&
        this.userInfo.departName &&
        this.userInfo.departName.includes("生产")
      );
    },
  },

  onLoad() {
    this.initPage();
  },

  onShow() {
    this.refreshUserInfo();
  },

  onReady() {
    // 监听编辑页面返回后的刷新事件
    uni.$on("refreshProfile", () => {
      this.loadUserInfo();
      // 如果是生产员工，重新加载工种信息
      if (this.isProductionEmployee) {
        this.loadUserWorkTypes();
      }
    });
  },

  onUnload() {
    // 移除事件监听
    uni.$off("refreshProfile");
  },

  methods: {
    initPage() {
      if (!authService.isLoggedIn()) {
        uni.reLaunch({
          url: "/pages/login/login",
        });
        return;
      }

      this.loadUserInfo();
      this.loadSettings();
    },

    loadUserInfo() {
      this.userInfo = uni.getStorageSync(USER_INFO) || {};
      this.currentRole = authService.getCurrentRole();

      // 获取登录类型
      this.loginType = uni.getStorageSync("erp_login_type") || "";

      // 如果是生产员工，加载工种信息
      if (this.isProductionEmployee) {
        this.loadUserWorkTypes();
      }
    },

    // 加载用户掌握的工种信息
    async loadUserWorkTypes() {
      try {
        if (!this.userInfo.id) {
          console.error("用户ID为空，无法加载工种信息");
          return;
        }

        const response = await employeeWorkTypeApi.getEmployeeWorkTypes(
          this.userInfo.id
        );
        console.log("工种信息API响应:", response);

        if (response.data.success && response.data.result) {
          this.userWorkTypes = response.data.result.map((workType) => ({
            name: workType.workTypeName || "未知工种",
            level: workType.skillLevel || 1,
            levelClass: this.getSkillLevelClass(workType.skillLevel),
            status: workType.status,
          }));
        } else {
          this.userWorkTypes = [];
        }
      } catch (error) {
        console.error("加载工种信息失败:", error);
        this.userWorkTypes = [];
      }
    },

    // 根据技能等级获取样式类名
    getSkillLevelClass(level) {
      const levelMap = {
        1: "level-basic", // 基础
        2: "level-skilled", // 熟练
        3: "level-expert", // 专家
      };
      return levelMap[level] || "level-basic";
    },

    loadSettings() {
      try {
        const savedSettings = uni.getStorageSync("app_settings");
        if (savedSettings) {
          this.settings = { ...this.settings, ...savedSettings };
        }
      } catch (error) {
        console.error("加载设置失败:", error);
      }
    },

    saveSettings() {
      try {
        uni.setStorageSync("app_settings", this.settings);
      } catch (error) {
        console.error("保存设置失败:", error);
      }
    },

    getSexText(sex) {
      const sexMap = {
        1: "男",
        2: "女",
      };
      return sexMap[sex] || "未设置";
    },

    formatDate(dateStr) {
      if (!dateStr) return "";
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
        2,
        "0"
      )}-${String(date.getDate()).padStart(2, "0")}`;
    },

    changeAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ["compressed"],
        sourceType: ["album", "camera"],
        success: (res) => {
          // 这里应该上传头像到服务器
          uni.showToast({
            title: "头像上传功能待开发",
            icon: "none",
          });
        },
      });
    },

    editProfile() {
      uni.navigateTo({
        url: "/pages/profile/edit",
      });
    },

    changePassword() {
      uni.navigateTo({
        url: "/pages/profile/change-password",
      });
    },

    aboutApp() {
      uni.navigateTo({
        url: "/pages/profile/about",
      });
    },

    togglePushNotification(e) {
      this.settings.pushNotification = e.detail.value;
      this.saveSettings();
    },

    toggleSoundAlert(e) {
      this.settings.soundAlert = e.detail.value;
      this.saveSettings();
    },

    toggleVibration(e) {
      this.settings.vibration = e.detail.value;
      this.saveSettings();
    },

    toggleTaskReminder(e) {
      this.settings.taskReminder = e.detail.value;
      this.saveSettings();
    },

    toggleQualityReminder(e) {
      this.settings.qualityReminder = e.detail.value;
      this.saveSettings();
    },

    logout() {
      uni.showModal({
        title: "确认退出",
        content: "确定要退出登录吗？",
        success: (res) => {
          if (res.confirm) {
            authService.logout();
          }
        },
      });
    },

    refreshUserInfo() {
      authService.refreshUserInfo().then(() => {
        this.loadUserInfo();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.profile-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.user-info-card {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;

  .avatar-wrapper {
    position: relative;

    .avatar-edit {
      position: absolute;
      bottom: 0;
      right: 0;
      width: 48rpx;
      height: 48rpx;
      border-radius: 50%;
      background-color: #1890ff;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 4rpx solid white;

      .cuIcon {
        font-size: 24rpx;
      }
    }
  }

  .role-tag {
    display: inline-flex;
    align-items: center;
    padding: 8rpx 16rpx;
    border-radius: 16rpx;
    font-size: 24rpx;
  }
}

.info-section,
.work-section,
.function-menu {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
}

.section-title {
  border-bottom: 1rpx solid #f0f0f0;
}

.info-item,
.menu-item {
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  .info-icon,
  .menu-icon {
    font-size: 32rpx;
    width: 32rpx;
  }
}

.logout-section {
  margin: 0 24rpx 24rpx;
}

.work-types {
  display: flex;
  flex-wrap: wrap;
  gap: 8rpx;

  .work-type-tag {
    display: inline-block;
    padding: 4rpx 12rpx;
    border-radius: 12rpx;
    font-size: 24rpx;
    color: white;

    &.level-basic {
      background-color: #52c41a; // 绿色 - 基础
    }

    &.level-skilled {
      background-color: #1890ff; // 蓝色 - 熟练
    }

    &.level-expert {
      background-color: #f5222d; // 红色 - 专家
    }
  }
}

.settings-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;

  .settings-content {
    background-color: white;
    border-radius: 12rpx;
    margin: 0 48rpx;
    width: calc(100% - 96rpx);
    max-height: 80vh;
    overflow: hidden;

    .settings-header {
      border-bottom: 1rpx solid #f0f0f0;
      position: relative;

      .cuIcon-close {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        font-size: 32rpx;
        color: #999;
      }
    }

    .setting-item {
      border-bottom: 1rpx solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }
    }
  }
}
</style>
